<!-- 员工请假列表 -->
<template>
  <ContainerLayoutV2 ref="containerLayoutRef" class="users-leave-list">
    <template #form>
      <el-form ref="formRef" :inline="true" :model="queryForm" class="query-form" label-width="40px">
        <UserInput v-model="queryForm.user" />
        <DeptCascader v-model="queryForm.deptIds" :multiple="false" />
        <el-form-item label="项目" v-if="false">
          <el-select v-model="queryForm.projectId" placeholder="请选择项目" clearable style="width: 160px">
            <el-option v-for="item in projectList" :key="item.code" :label="`${item.code}-${item.cname}`" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="queryForm.leaveCategory" placeholder="请选择类型" clearable style="width: 130px">
            <el-option v-for="item in holidayCategoryList" :key="item.dictValue" :label="`${item.dictLabel}`" :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.leaveStatus" placeholder="请选择状态" clearable style="width: 130px">
            <el-option v-for="item in leaveStatusOptions" :key="item.value" :label="`${item.label}`" :value="item.value" />
          </el-select>
        </el-form-item>
        <TimeSlotDatePicker label="时段" v-model="queryForm.date" />
        <el-form-item>
          <el-button type="primary" @click="handleClickBtnSubmit" :icon="Search">查询</el-button>
          <el-button @click="handleClickBtnReset" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </template>
    <template #toolbar>
      <ExcelExportButton :headerParams="exportHeaderParams" :table-data="exportTableData" fileName="员工请假信息表" />
    </template>
    <template #tables>
      <div class="table-wrap" ref="tableWrap">
        <el-table :data="tableData" v-loading="isTableLoading" style="width: 100%" border :height="tableHeight" header-cell-class-name="table-header-row" empty-text="没有数据">
          <el-table-column prop="nickName" label="姓名" width="150" fixed />
          <el-table-column>
            <template #header>
              <div style="text-align: center">{{ tableColumnHead }}类型</div>
            </template>
            <el-table-column v-for="item in holidayCategoryList" :label="item.dictLabel" width="100">
              <template #default="scope">
                {{ scope.row[`leaveCategory${item.dictValue}`] }}
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column />
          <el-table-column label="操作" width="210" fixed="right">
            <template #default="scope">
              <el-button link type="primary" @click="handleClickBtnDetail(scope.row)" size="small" :icon="Document">详细信息</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </template>
  </ContainerLayoutV2>
  <DialogUsersLeaveDetail ref="dialogUsersLeaveDetailRef" />
</template>
<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import ContainerLayoutV2 from '../layout/ContainerLayoutV2.vue'
import * as utils from '../utils'
import { useProjectssStore, useUsersStore, useHolidayCategoryStore } from '../stores'
import { Refresh, Search, Document } from '@element-plus/icons-vue'
import { leaveStatusEnum } from '../definitions/status'
import api from '../api'
import TimeSlotDatePicker from '../layout/FormTableLayout/TimeSlotDatePicker.vue'
import ExcelExportButton from '../layout/ButtonToolbar/ExcelExportButton.vue'
import UserInput from '../layout/FormTableLayout/UserInput.vue'
import DeptCascader from '../layout/FormTableLayout/DeptCascader.vue'
import DialogUsersLeaveDetail from '../components/dialog/DialogUsersLeaveDetail.vue'
import { ElMessage } from 'element-plus'

const dialogUsersLeaveDetailRef = ref<InstanceType<typeof DialogUsersLeaveDetail> | null>(null)
const containerLayoutRef = ref<InstanceType<typeof ContainerLayoutV2> | null>(null)

const tableData = ref<any[]>([])
const tableColumnHead = ref('')
const tableWrap = ref<HTMLElement | null>(null)
const tableHeight = ref(500)
const holidayCategoryList = ref(useHolidayCategoryStore().getAllState())
const isTableLoading = ref(false)
const exportTableData = ref<any[]>([])
const exportHeaderParams: any[] = [
  { title: '姓名', value: 'nickName', width: 20 },
  {
    title: '类型',
    children: [],
  },
]
holidayCategoryList.value.forEach((item: any) => {
  exportHeaderParams[1].children.push({ title: item.dictLabel, value: `leaveCategory${item.dictValue}`, width: 15 })
})
const projectList = ref<Array<{ id: number; code: string; cname: string }>>(useProjectssStore().getAllState() as any)
const queryForm = reactive({
  user: '',
  projectId: null,
  date: [] as Date[],
  deptIds: [] as any[] | number[],
  leaveStatus: null,
  leaveCategory: null,
})

const leaveStatusOptions = ref<any[]>([])

Object.keys(leaveStatusEnum).map((value: any) => {
  const label = leaveStatusEnum[value]
  if (typeof label === 'string' && value !== '3') {
    leaveStatusOptions.value.push({
      label,
      value,
    })
  }
})
/**
 * 获取用户列表
 *
 * 该函数根据查询表单（queryForm）中的条件，筛选出符合条件的用户列表并赋值给 tableData.value。
 *
 * 筛选条件包括用户名（user）和部门ID（deptIds）。
 *
 * @returns 无返回值
 */
const getUsersList = () => {
  const deptIds = queryForm.deptIds[queryForm.deptIds.length - 1]
  return useUsersStore().userAllList.filter((item: any) => {
    // 用户名条件：如果queryForm.user不为空，则必须匹配，否则为true
    const userCondition = queryForm.user === '' || item.userName == queryForm.user

    // 部门条件：如果deptId不为空，则必须匹配 否则为true
    const deptCondition = deptIds == null || item.deptId == deptIds

    // 只有非空的条件才会参与过滤
    return userCondition && deptCondition
  })
}
/**
 * 获取考勤分类列表
 *
 * @returns {Promise<void>}
 */
const getDataList = async () => {
  isTableLoading.value = true
  const [start, end] = queryForm.date
  const params = {
    pageSize: 99999,
    startLeaveDate: utils.formatDate(start, 'yyyy-MM-dd'),
    endLeaveDate: utils.formatDate(end, 'yyyy-MM-dd'),
  }
  // 设置 table 列
  tableColumnHead.value = `${params.startLeaveDate} - ${params.endLeaveDate}`

  const deptIds = queryForm.deptIds[queryForm.deptIds.length - 1]
  if (deptIds != null) {
    Object.assign(params, { deptId: deptIds })
  }
  if (queryForm.leaveCategory) {
    Object.assign(params, { leaveCategory: queryForm.leaveCategory })
  }
  if (queryForm.leaveStatus) {
    Object.assign(params, { leaveStatus: queryForm.leaveStatus })
  }
  if (queryForm.projectId) {
    Object.assign(params, { projectId: queryForm.projectId })
  }
  if (queryForm.user !== '') {
    Object.assign(params, { userName: queryForm.user })
  }
  // 员工请假信息
  const leaveList = await api.Leave.getList(params)

  // 统计每个 userId + leaveCategory 组合的出现次数
  const userLeaveCategoryCountMap = leaveList.reduce((acc: Record<string, number>, item: any) => {
    const key = `${item.userId}_${item.leaveCategory}` // 使用复合键
    acc[key] = (acc[key] || 0) + 1
    return acc
  }, {})

  // 转换统计结果为数组形式
  const userLeaveStatistics = Object.entries(userLeaveCategoryCountMap).map(([key, count]) => {
    const [userId, leaveCategory] = key.split('_')
    return {
      userId: Number(userId),
      leaveCategory: leaveCategory,
      count: count,
    }
  })

  // 员工列表
  const rows = getUsersList().map((item: any) => {
    //  item
    holidayCategoryList.value.forEach((e: any) => {
      item[`leaveCategory${e.dictValue}`] = 0
    })
    item['leaveList'] = leaveList.filter((e1: any) => e1.userId == item.userId)
    userLeaveStatistics
      .filter((e2: any) => e2.userId == item.userId)
      .forEach((e3: any) => {
        item[`leaveCategory${e3.leaveCategory}`] = e3.count
      })
    return item
  })
  exportTableData.value = rows
  tableData.value = rows
  isTableLoading.value = false
}
/**
 * 重置表单
 *
 * 重置查询表单的所有字段到初始状态，包括用户、项目ID、日期范围、部门ID数组和时间日志类别
 */
const resetForm = () => {
  tableData.value = []
  const [start, end] = utils.getDateRangeByDate(utils.shortcutsType.本月) as Date[]
  queryForm.date = [start, end]
  queryForm.user = ''
  queryForm.projectId = null
  queryForm.deptIds = [] as string[] | number[]
  queryForm.leaveStatus = null
  handleClickBtnSubmit()
}
/**
 * 处理点击提交按钮的事件
 *
 * 异步调用获取请假分类列表的函数
 */
const handleClickBtnSubmit = async () => {
  await getDataList()
}

/**
 * 处理点击重置按钮的事件
 *
 * 调用 resetForm 函数重置表单
 */
const handleClickBtnReset = async () => {
  await resetForm()
}

const handleClickBtnDetail = async (row: any) => {
  if (row.leaveList.length > 0) {
    dialogUsersLeaveDetailRef.value?.open(row)
  } else {
    ElMessage.warning('该用户没有请假信息')
  }
}

onMounted(async () => {
  const [start, end] = utils.getDateRangeByDate(utils.shortcutsType.本月) as Date[]
  queryForm.date = [start, end]
  nextTick(() => {
    if (containerLayoutRef.value && containerLayoutRef.value.tableContainer) {
      const tableContainer = containerLayoutRef.value.tableContainer
      tableHeight.value = tableContainer.offsetHeight
    }
  })
})
</script>
<style lang="scss" scoped>
.overitem-list {
  display: flex;
  flex-direction: column;
  .form-container {
    display: flex;
    justify-content: flex-start;
  }
  .table-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    .table-wrap {
      flex: 1;
    }
  }
  .button-toolbar {
    margin-bottom: 18px;
  }
  .table-header-cell {
    writing-mode: vertical-lr;
  }
  .remark-content {
    width: 100%;
    height: 100%;
    white-space: pre-line;
  }
}
</style>
